package com.lanwf.admin.interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.lanwf.common.model.SysAdmin;
import com.lanwf.common.model.SysOplog;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Enumeration;

/**
 * @Auther: Lanwf
 * @Date: 2022/8/16 16:02
 * @Description: 操作日志记录
 */
public class OpLogInterceptor implements Interceptor {


    //带有这些个名字的加入到日志操作中
    String[] includeNames = {"save","update","delete","onLock","offLock"};

    @Override
    public void intercept(Invocation invocation) {
        HttpServletRequest request = invocation.getController().getRequest();
        String requestURI = request.getRequestURI();
        SysOplog o = null;
        long startTime = System.currentTimeMillis();
        if(allowAddLog(requestURI)){
            SysAdmin sysAdmin =(SysAdmin)request.getAttribute("account");
            o = new SysOplog();
            o.setCreateTime(new Date());
            o.setMethodname(methodName(requestURI));
            o.setClassname(requestURI);

            String params = "";

            Enumeration<String> parameterNames = invocation.getController().getParaNames();
            while (parameterNames.hasMoreElements()){

                String k = parameterNames.nextElement();
                String v = invocation.getController().get(k);
                params += k + ":" + v + " ";
            }
            o.setParams(params);
            o.setUsername(sysAdmin.getUsername());
        }

        invocation.invoke();

        if(o != null){
            long spendTimes =  System.currentTimeMillis() - startTime;
            o.setTimes(spendTimes+"ms");
            o.save();
        }
    }

    /**
     * allow add log
     * @param requestURI
     * @return
     */
    private boolean allowAddLog(String requestURI){
        if(requestURI.contains("oplog")){
            return false;
        }
        for (int i = 0; i < includeNames.length; i++) {
            if(requestURI.contains(includeNames[i])){
                return true;
            }
        }
        return false;
    }


    /**
     * method name
     * @param requestURI
     * @return
     */
    private String methodName(String requestURI){
        if(requestURI.contains("save")){
            return "增加";
        }
        if(requestURI.contains("update")){
            return "修改";
        }
        if(requestURI.contains("delete")){
            return "删除";
        }
        if(requestURI.contains("onLock")){
            return "上锁";
        }
        if(requestURI.contains("offLock")){
            return "解锁";
        }
        return "其他";
    }
}
